<?php

namespace app\index\controller;

use app\BaseController;
use app\index\diyclass\Interal;
use app\index\diyclass\Task;
use app\index\model\PhotoList as PhotoListModal;
use app\index\model\UserModel;
use app\index\validate\LoginValidate;
use app\index\model\IntergralLog;
use email\Email;
use Firebase\JWT\JWT;
use think\facade\Db;
use think\Request;

class User extends BaseController
{
    protected $middleware = [
        'Auth' => ['except' => ['login', 'register', 'getUser']],
        'Openness' => ['only' => ['getUser']],
    ];

    public function sendcode(Request $request)
    {
        $params = $this->request->post(['email']);
        if($params['email'] != $this->request->user['email']) {
            return result()->fail("原邮箱不正确", 500);
        }
        $code = rand_number(6);
        $emailInfo = new Email($params['email']);
        $emailInfo->setTitle("验证码");
        $emailInfo->setBody("您的验证码是：".$code);
        if(!$emailInfo->send()) {
            return result()->fail("验证码发送失败", 500);
        }
        $cacheKey = $params['email'].'email';
        cache($cacheKey, $code, 60);
        return result()->success("验证码已发送到您的邮箱");
    }

    public function updemail()
    {
        $params = $this->request->post(['email', 'smsCode']);
        $cacheKey = $params['email'].'email';
        $cacheCode = cache($cacheKey);
        if (!$cacheCode) {
            return result()->fail("验证码已过期", 400);
        }
        if ($cacheCode !== $params['smsCode']) {
            return result()->fail("验证码不正确", 400);
        }
        $sql = new UserModel();
        $sql->update(['email' => $params['email']], ['id' => $this->request->user['id']]);
        return result()->onlySucMsg("修改成功");
    }

    public function userinfo(Request $request) {
        $birthdayArr = explode('-', $request->user['birthday']);
        $birthdayArr = array_map('intval', $birthdayArr);
        $request->user['birthdayArr'] = $birthdayArr;
        if($request->user['sign_at']) {
            $today = date("Y-m-d");
            if (date("Y-m-d", $request->user['sign_at']) == $today) {
                $request->user['is_sign'] = true;
            } else {
                $request->user['is_sign'] = false;
            }
        } else {
            $request->user['is_sign'] = false;
        }
        $sql = new UserModel();
        $childerCount = $sql->where('superiorUserId', $request->user->id)->count();
        $request->user['childercount'] = $childerCount;
        $photoSql = new PhotoListModal();
        $request->user['workNum'] = $photoSql->where('releaseid', $request->user['id'])->count();
        return result()->success($request->user);
    }
    public function interlog(Request $request)
    {
        $params = $this->request->post(['current', 'size']);
        $whereArr[] = ['userId', '=', $request->user['id']];
        $sql = new IntergralLog();
        $list = $sql
            ->where($whereArr)
            ->order('create_at desc')
            ->page($params['current'])
            ->limit($params['size'])
            ->select();
        return result()->success($list);
    }
    public function expenditureLog()
    {
        $params = $this->request->post(['current', 'size']);
        $whereArr[] = ['userId', '=', $this->request->user['id']];
        $whereArr[] = ['type', 'in', ['BUY_PHOTO']];
        $sql = new IntergralLog();
        $list = $sql
            ->where($whereArr)
            ->order('create_at desc')
            ->page($params['current'])
            ->limit($params['size'])
            ->select();
        foreach ($list as $key => $value) {
            if($value['type'] == 'BUY_PHOTO') {
                $list[$key]['photoInfo'] = $value->photoInfo;
            }
        }
        return result()->success($list);
    }

    public function revenueLog()
    {
        $params = $this->request->post(['current', 'size']);
        $whereArr[] = ['userId', '=', $this->request->user['id']];
        $whereArr[] = ['type', 'in', ['SIGN', 'SELL_PHOTO']];
        $sql = new IntergralLog();
        $list = $sql
            ->where($whereArr)
            ->order('create_at desc')
            ->page($params['current'])
            ->limit($params['size'])
            ->with('photoInfo')
            ->select();
        return result()->success($list);
    }

    public function userTask(Request $request) {
        $task = new Task($request->user['id'], 'COMMENT_TASK');
        $arr[] = $task->getTaskInfo();
        $task->setKey('ADD_TAG_TASK');
        $arr[] = $task->getTaskInfo();
        return result()->success($arr);
    }
    public function sign(Request $request)
    {
        $today = date("Y-m-d");
        $yesterday = date("Y-m-d", strtotime("-1 day"));
        $params = [
            'signDay' => $request->user['signDay'],
            'sign_at' => time()
        ];
        if ($request->user['sign_at']) {
            if(date("Y-m-d", $request->user['sign_at']) == $today) {
                return result()->fail("请不要重复签到", 500);
            }
            if(date("Y-m-d", $request->user['sign_at']) == $yesterday) {
                $params['signDay'] = $params['signDay'] + 1;
            } else {
                $params['signDay'] = 1;
            }
        } else {
            $params['signDay'] = 1;
        }
        Db::startTrans();
        try {
            $sql = new UserModel();
            $sql->update($params, ['id' => $request->user->id]);
            $signInter = sign_day_integral($params['signDay']);
            $log = new Interal($request->user->id,'SIGN');
            $log->setNum($signInter);
            $log->setContent("签到第".$params['signDay'].'天');
            $log->save();
            Db::commit();
            return result()->success($signInter);
        } catch (\Throwable $th) {
            Db::rollback();
            return result()->fail($th->getMessage(), 500);
        }
    }

    public function edit(Request $request) {
        $params = $this->request->post(['avatar', 'nickname', 'showHome', 'remark', 'header', 'birthday', 'relname', 'sex', 'age', 'city', 'address']);
        $sql = new UserModel();
        $sql->update($params, ['id' => $request->user->id]);
        return result()->onlySucMsg("修改成功");
    }

    public function login()
    {
        $params = $this->request->post(['email', 'password']);
        $validate = new LoginValidate();
        if (!$validate->scene('login')->check($params)) {
            return result()->fail($validate->getError(), 500);
        }
        $sql = new UserModel();
        $user = $sql->where('email', $params['email'])->limit(1)->findOrEmpty();
        if ($user->isEmpty()) {
            return result()->fail("该账号不存在", 400);
        }
        $pass = md5($params['password'] . $user->salt);
        if ($pass !== $user->password) {
            return result()->fail("密码输入不正确", 500);
        }
        $payload = array(
            "iat" => time(), // 签发时间
            "ext" => strtotime("7 day"), // 过期时间
            "data" => [
                'id' => "USER:" . $user->id,
                'password' => $user->password
            ]
        );
        $token = JWT::encode($payload, config('app.jwt.secret'), config('app.jwt.algo'));
        event('UserLogin', $user);
        return result()->success($token, '登录成功');
    }

    public function register() {
        $params = $this->request->post(['email', 'code', 'password', 'pid']);
        $validate = new LoginValidate();
        if (!$validate->scene('register')->check($params)) {
            return result()->fail($validate->getError(), 500);
        }
        $sql = new UserModel();
        $pid = isset($params['pid']) ? $params['pid'] : null;
        if($pid) {
            if(!$sql->checkInvitationCode($pid)) {
                return result()->fail("邀请链接不正确", 500);
            }
        }
        $cacheKey = $params['email'].'register';
        $cacheCode = cache($cacheKey);
        if (!$cacheCode) {
            return result()->fail("验证码已过期", 400);
        }
        if ($cacheCode !== $params['code']) {
            return result()->fail("验证码不正确", 400);
        }
        $user = $sql->where('email', $params['email'])->limit(1)->findOrEmpty();
        if (!$user->isEmpty()) {
            return result()->fail("该账号已存在", 400);
        }
        $params['nickname'] = "小白用户".rand_letter(6);
        $params['header'] = "https://bc-haowanjia.oss-cn-hangzhou.aliyuncs.com/file/1689756841389126.png";
        $params['password'] = md5($params['password']);
        $params['invitationCode'] = $this->getInvitationCode();
        Db::startTrans();
        try {
            $sql->save($params);
            if($pid) {
                $log = new Interal($pid,'INVITE');
                $log->setNum(300);
                $log->setContent("邀请好友注册");
                $log->save();
                $userLog = new Interal($user->id,'REGISTER');
                $userLog->setNum(300);
                $userLog->setContent("填写邀请码");
                $userLog->save();
            }
            Db::commit();
            return result()->success("注册成功");
        }  catch (\Throwable $th) {
            Db::rollback();
            return result()->fail($th->getMessage(), 500);
        }
    }

    protected function getInvitationCode()
    {
        $code = make_coupon_card();
        $sql = new UserModel();
        if(!$sql->checkInvitationCode($code)) {
            return $code;
        } else {
            return $this->getInvitationCode();
        }
    }

    public function getUser()
    {
        $params = $this->request->get(['id']);
        $sql = new UserModel();
        $user = $sql
            ->where('id', $params['id'])
            ->hidden(['password', 'comment_bg_id'])
            ->withCount(['photoNum', 'concern', 'fans', 'coll'])
            ->find();
        if(empty($this->request->user)) {
            $user['isFollow'] = false;
        } else {
            $user['isFollow'] = $sql->checkFollow($this->request->user['id']);
        }
        return result()->success($user);
    }
}